<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <el-row :gutter="20" slot-scope="{ row }">
        <el-col :span="4">
          <el-button name="add" type="primary" @click="addOrRedact(row)"
            >新增角色</el-button
          >
        </el-col>
      </el-row>
    </el-card>

    <!-- 表格区域 -->
    <el-table :data="roleList" style="width: 100%" border stripe>
      <!-- 扩展列 -->
      <el-table-column type="expand">
        <template slot-scope="{ row }">
          <el-row
            class="btbottom vcenter"
            :class="{ bttop: i1 === 0 }"
            v-for="(level1, i1) in row.children"
            :key="level1.id"
          >
            <!-- 一级权限 -->
            <el-col :span="5">
              <el-tag closable @close="deleteRights(row, level1.id)">{{
                level1.authName
              }}</el-tag>
              <i class="el-icon-caret-right"></i>
            </el-col>
            <!-- 二级权限和三级权限 -->
            <el-col :span="19">
              <!-- 方式1.传字符串 -->
              <!-- <el-row :class="i2!==0?'bttop': ''"> -->
              <!-- 方式2.传数组 -->
              <!-- <el-row :class="[i2!==0?'bttop': '']"> -->
              <!-- 方式3.传对象 -->
              <!-- <el-row :class="{'bttop':i2!==0}"> -->
              <el-row
                class="vcenter"
                :class="{ bttop: i2 !== 0 }"
                v-for="(level2, i2) in level1.children"
                :key="level2.id"
              >
                <!-- 二级 -->
                <el-col :span="6">
                  <el-tag
                    type="success"
                    closable
                    @close="deleteRights(row, level2.id)"
                    >{{ level2.authName }}</el-tag
                  >
                  <i class="el-icon-caret-right"></i>
                </el-col>
                <!-- 三级 -->
                <el-col :span="18">
                  <el-tag
                    v-for="level3 in level2.children"
                    :key="level3.id"
                    type="warning"
                    closable
                    @close="deleteRights(row, level3.id)"
                    >{{ level3.authName }}</el-tag
                  >
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </template>
      </el-table-column>
      <el-table-column type="index" label="#" width="50"> </el-table-column>
      <el-table-column prop="roleName" label="角色名称"> </el-table-column>
      <el-table-column prop="roleDesc" label="角色描述"> </el-table-column>
      <el-table-column label="操作" width="320">
        <template slot-scope="{ row }">
          <el-button
            name="redact"
            type="primary"
            size="mini"
            icon="el-icon-edit"
            @click="addOrRedact(row)"
            >编辑</el-button
          >
          <el-button
            type="danger"
            size="mini"
            icon="el-icon-delete"
            @click="delectRole(row)"
            >删除</el-button
          >
          <el-tooltip content="分配权限" placement="top" :enterable="false">
            <el-button
              type="warning"
              size="mini"
              icon="el-icon-setting"
              @click="showRightsDialog(row)"
              >分配权限</el-button
            >
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加角色对话框 -->
    <el-dialog
      :title="(sureAddOrRedact === 'add' ? '新增' : '编辑') + '角色'"
      :visible.sync="sureAdd"
      width="30%"
      @close="closeSureAdd"
      :before-close="handleClose"
    >
      <el-form
        ref="addroleForm"
        :model="newroleList"
        label-width="80px"
        :rules="rules"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="newroleList.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="newroleList.roleDesc"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="sureAdd = false">取 消</el-button>
        <el-button type="primary" @click="addOrRedactMethod">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配权限对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="showRightsDialogVisible"
      width="50%"
      :before-close="handleClose"
    >
      <el-tree
        :data="rightsList"
        :props="{ label: 'authName' }"
        show-checkbox
        default-expand-all
        node-key="id"
        :default-checked-keys="defKeys"
        ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showRightsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      roleList: [], // 定义权限列表数据
      rightsList: [], // 获取所有权限
      defKeys: [], // 默认选中的权限
      roleId: [],
      newroleList: {
        roleName: '',
        roleDesc: ''
      }, // 新增角色数据列表
      sureAddOrRedact: '',
      sureAdd: false, // 是否打开添加角色对话框
      showRightsDialogVisible: false, // 是否打开分配权限对话框
      // showEditDialogVisible: false, // 是否打开编辑角色对话框
      rules: {
        roleName: [
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请选择角色描述', trigger: 'blur' }
        ]
      },
      RedactRole: []// 编辑角色对象
    }
  },
  created () {
    // 调用获取权限列表的方法
    this.getRoleList()
  },

  methods: {
    // 判断使用什么方法
    addOrRedactMethod () {
      if (this.sureAddOrRedact === 'add') {
        this.addrole()
      } else {
        this.redactRole()
      }
    },
    // 判断是新增还是编辑
    addOrRedact (row) {
      if (row === undefined) {
        this.sureAddOrRedact = 'add'
      } else {
        // 将必要的数据传入对应的地方
        this.sureAddOrRedact = 'redact'
        this.RedactRole = row
        // 通过id获取角色信息
        this.queryRole()
      }
      // 相关数据准备好了之后在打开对话框
      this.sureAdd = true
    },
    // 是否关闭对话框
    handleClose (done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done()
        })
        .catch(_ => {})
    },

    // 打开分配权限对话框
    async showRightsDialog (role) {
      this.roleId = role.id
      this.defKeys = []
      const { data: res } = await this.$http.get('rights/tree ')
      this.rightsList = res.data
      // 方式1.不用递归
      /*
      const rights = role.children
      rights.forEach(level1 => {
        level1.children.forEach(level2 => {
          level2.children.forEach(level3 => {
            this.defKeys.push(level3.id)
          })
        })
      })
      */
      // 方式2.1.用递归,简化版本
      /*
      this.getLeafKeys(role)
      getLeafKeys (item) {
        if (!item.children) {
          this.defKeys.push(item.id)
        } else {
          item.children.forEach(subItem => {
            this.getLeafKeys(subItem)
          })
        }
      },
      */
      this.getLeafKeys(role, this.defKeys)
      this.showRightsDialogVisible = true
    },
    // 关闭新增角色对话框事件
    closeSureAdd () {
      // 关闭对话框后，需要把文本框里的内容清空
      this.$refs.addroleForm.resetFields()
    },
    // 新增角色
    addrole () {
      // 新增角色预校验
      this.$refs.addroleForm.validate(async (valid) => {
        if (!valid) return
        // 发送新增角色的异步请求
        const { data: res } = await this.$http.post('roles', this.newroleList)
        // 判断是否成功添加角色
        if (res.meta.status !== 201) {
          return this.$message.error('新增角色失败')
        }
        this.$message({
          message: '新增角色成功',
          type: 'success',
          showClose: true,
          duration: 3000
        })
        // 重新渲染页面
        this.getRoleList()
        // 关闭新增角色对话框
        this.sureAdd = false
      })
    },
    async queryRole () {
      // 根据 ID 查询角色
      const { data: res } = await this.$http.get(`roles/${this.RedactRole.id}`)
      // 将角色的数据存入data
      this.newroleList.roleName = res.data.roleName
      this.newroleList.roleDesc = res.data.roleDesc
      this.sureAdd = true
    },
    // 编辑角色
    redactRole () {
      // 编辑角色预校验
      this.$refs.addroleForm.validate(async (valid) => {
        if (!valid) return
        // 发送编辑角色的异步请求
        const { data: res } = await this.$http.put(`roles/${this.RedactRole.id}`, this.newroleList)
        // 判断是否成功添加角色
        if (res.meta.status !== 200) {
          return this.$message.error('编辑角色失败')
        }
        this.$message({
          message: '编辑角色成功',
          type: 'success',
          showClose: true,
          duration: 3000
        })
        // 重新渲染页面
        this.getRoleList()
        // 关闭编辑角色对话框
        this.sureAdd = false
      })
    },
    // 删除角色
    async delectRole (row) {
      console.log(row.id)
      const { data: res } = await this.$http.delete(`roles/${row.id}`)
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('删除角色失败')
      }
      this.$message({
        message: '删除角色成功',
        type: 'success',
        showClose: true,
        duration: 3000
      })
      // 重新渲染页面
      this.getRoleList()
    },

    // 方式2.2.用递归,标准版本
    getLeafKeys (item, arr) {
      if (!item.children) {
        arr.push(item.id)
      } else {
        item.children.forEach(subItem => {
          this.getLeafKeys(subItem, arr)
        })
      }
    },

    // 异步获取权限列表
    async getRoleList () {
      const { data: resBody } = await this.$axios.get('roles')
      this.roleList = resBody.data
    },

    // 删除权限
    deleteRights (row, rightId) {
      const roleId = row.id
      // 确认是否删除
      this.$confirm('确认删除?', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async action => {
        const { data: resBody } = await this.$http.delete(`roles/${roleId}/rights/${rightId}`)
        row.children = resBody.data
        this.$message({
          message: '操作成功',
          type: 'success',
          showClose: true,
          duration: 3000

        })
      }).catch(() => {

      })
    },

    // 添加权限
    async setRights () {
      const rids = [...this.$refs.treeRef.getHalfCheckedKeys(), ...this.$refs.treeRef.getCheckedKeys()]
      // 发送请求
      await this.$http.post(`roles/${this.roleId}/rights`, { rids: rids.join(',') })
      // 刷新列表
      this.getRoleList()
      // 提示
      this.$message({
        message: '操作成功',
        type: 'success',
        showClose: true,
        duration: 3000
      })
      // 关闭对话框
      this.showRightsDialogVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bttop {
  border-top: 1px solid #eee;
}
.btbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  //垂直居中
  align-items: center;
}
</style>
